import init from '@feidao/web/framework/browser/d/component';
import { id, spaceid, systemid, refsystemid } from './config';
import { IFeidaoAiBrowserComponent } from '@feidao/web/interfaces';
import storage_get from '@feidao/web/atom/browser/storage/get';
import storage_clear from '@feidao/web/atom/browser/storage/clear';
import ui_get_dom_by_id from '@feidao/web/atom/browser/ui/get-dom-by-id';
import ui_set_html from '@feidao/web/atom/browser/ui/set-html';
import user_loginout from '@feidao/web/atom/browser/msg/user-logout';
import url_redirect from '@feidao/web/atom/browser/url/direct-to'
import { send_msg as url } from './config';
import fire from '@feidao/web/atom/browser/msg/fire';

const actions = {
	async init(fd: IFeidaoAiBrowserComponent, ...args: any[]) {
		const nowtime = new Date();
		const year = nowtime.getFullYear();
		const month = nowtime.getMonth() + 1;
		const date = nowtime.getDate();
		fd.data.node.querySelector<HTMLDivElement>('[data-feidao-time]').innerText = year + "年" + month + "月" + date + "日" + " " + nowtime.toLocaleTimeString('chinese', { hour12: false });
		setInterval((() => {
			const nowtime = new Date();
			const year = nowtime.getFullYear();
			const month = nowtime.getMonth() + 1;
			const date = nowtime.getDate();
			fd.data.node.querySelector<HTMLDivElement>('[data-feidao-time]').innerText = year + "年" + month + "月" + date + "日" + " " + nowtime.toLocaleTimeString('chinese', { hour12: false });
		}), 1000);
		const userInfo = await storage_get('user');
		if (userInfo) {
			const g_d = ui_get_dom_by_id(fd.data.node, 'user_name');
			const g_c = ui_get_dom_by_id(fd.data.node, 'usercode') as HTMLAnchorElement;
			g_c.href = './alter-unit.html?register_user_no=' + userInfo.usercode;
			await ui_set_html(g_d, userInfo.user_name);
		}
	},
	async user_loginout(fd: IFeidaoAiBrowserComponent, ...args: any[]) {
		const userInfo = await storage_get('user');
		try {
			await user_loginout(url, fd.data.systemid, userInfo.usercode);
			await storage_clear('global');
			await storage_clear();
		} catch (error) {
			console.log(error)
		} finally {
			url_redirect('login.html', {});
		}
	},
	async select_role(fd: IFeidaoAiBrowserComponent, ...args: any[]) {
		await fire('zjc-000005', 'cmpt_show');
	},
	async update_pwd(fd: IFeidaoAiBrowserComponent, ...args: any[]) {
		await fire('zjc-000006', 'cmpt_show');
	}
};

const s = {
	'fd-events-init': 'init',
	'user_loginout': 'user_loginout',
	'select_role': 'select_role',
	'update_pwd': 'update_pwd',
};

export default function main(url: string, query: any) {

	return init(id, s, actions, url, query, { spaceid, systemid, refsystemid });
}
